package com.lau.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.lau.common.exception.DebugException;
import com.lau.entity.SysRoleMenu;
import com.lau.mapper.SysRoleMenuMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lau.entity.SysRole;
import com.lau.mapper.SysRoleMapper;
import com.lau.service.SysRoleService;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Lau
 * @since 2023-12-28
 */
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements SysRoleService {


	@Autowired
	SysRoleMapper roleMapper;
	@Autowired
	SysRoleMenuMapper roleMenuMapper;

	@Override
	@DS("slave1")
	public List<SysRole> listRolesByUserId(Long userId) {
        return this.list(new QueryWrapper<SysRole>()
				.inSql("id", "select role_id from sys_user_role where user_id = " + userId));
	}

	@Override
	public SysRole getSysRoleByRoleId(Long id) {
		if (id==null){
			throw new DebugException("id不能为空");
		}
		SysRole sysRole = roleMapper.selectById(id);
		// 获取角色相关联的菜单id
		List<SysRoleMenu> roleMenus = roleMenuMapper.selectList(new QueryWrapper<SysRoleMenu>().eq("role_id", id));
		List<Long> menuIds = roleMenus.stream().map(SysRoleMenu::getMenuId).collect(Collectors.toList());

		sysRole.setMenuIds(menuIds);
		return sysRole;
	}

	@Override
	public Page<SysRole> pageRoles(Page page, String roleName) {
		return roleMapper.selectPage(page,
				new QueryWrapper<SysRole>()
						.like(StrUtil.isNotBlank(roleName), "role_name", roleName));
	}

}
